package com.meiyou.service.impl;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;


import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;


import com.meiyou.mapper.MeiyouThirMapper;
import com.meiyou.mapper.MeiyouUserMapper;
import com.meiyou.mapper.UserMapperCustom;
import com.meiyou.pojo.Coordinate;
import com.meiyou.pojo.MeiyouThir;
import com.meiyou.pojo.MeiyouUser;
import com.meiyou.pojo.MeiyouUserExample;
import com.meiyou.pojo.BgadminExample.Criteria;
import com.meiyou.service.TecentService;
import com.meiyou.service.UserService;
import com.meiyou.test.RedisUtil;
import com.meiyou.utils.Base64Util;
import com.meiyou.utils.Context;
import com.meiyou.utils.FileUtil;
import com.meiyou.utils.GsonUtils;
import com.meiyou.utils.HttpUtil;
import com.meiyou.utils.Msg;
import com.meiyou.utils.ShareCodeUtil;

@Service
public class UserServiceImpl implements UserService{
   
	@Autowired
	MeiyouUserMapper usermapper;
	
	@Autowired
	UserMapperCustom userMapperCustom;
	
	@Autowired
	MeiyouThirMapper meiyouThirMapper;
	
	
	
	
	/**
	 * 用户手机号注册
	 */
	
	public Msg insUserRegist(String phone,String password,String uccount) {
		System.out.println("开启插入用户");
		Msg msg;
		// TODO Auto-generated method stub
		System.out.println("数量为"+usermapper.selectCountByphone(phone));
		if(usermapper.selectCountByphone(phone)>=1) {
			
			msg = Msg.fail();
			msg.setMsg("该手机号已被注册");
			return msg;
		}
		else {		
			System.out.println("注册密码:"+password);
			MeiyouUser user = new MeiyouUser();
			user.setuPhone(phone);
			user.setuOld(18);
			user.setuSex("男");
			user.setuPassword(password);
			user.setuTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			user.setuCount(uccount);//自动生成账号
			user.setuImg(Context.fwqaddress+"/default.jpg");
			TecentService tencent = new TencentServiceImpl();
			if(tencent.registTencent(user)) {
				if(usermapper.insert(user)==1) {
						msg = Msg.success();
						return msg;
				}else {
					msg = Msg.fail();
					msg.setMsg("本地用户注册失败，腾讯云成功");
					return msg;
				}
			}else {
				msg = Msg.fail();
				msg.setMsg("腾讯云账户注册失败");
				return msg;
				
			}
		}
	}
	
	
	public String selUserCount(String phone,double jindu,double weidu) {
		// TODO Auto-generated method stub
		if(usermapper.selectCountByphone(phone)>=1) {
			Coordinate coor = new Coordinate();
			coor.setLatitude(weidu);
			coor.setLongitude(jindu);
		    coor.setKey(phone);
		    RedisUtil.addReo(coor,"test");
		    System.out.println("添加位置信息成功");
			return usermapper.selectUcountByphone(phone);		
		}
		return null;
	}

	
	public int insUserSelective(MeiyouUser user) {
		// TODO Auto-generated method stub
		return usermapper.insertSelective(user);
		
	}

	
	public List<MeiyouUser> selPwdByCount(String ucount) {
		// TODO Auto-generated method stub
		
		MeiyouUserExample userexample = new MeiyouUserExample();
		MeiyouUserExample.Criteria creteria = userexample.createCriteria();
		creteria.andUCountEqualTo(ucount);	
	    return usermapper.selectByExample(userexample);
	}

	
	public boolean updPwd(String newpwd, String uphone) {
		Msg msg;
		// TODO Auto-generated method stub
		MeiyouUserExample userexample = new MeiyouUserExample();
		MeiyouUserExample.Criteria criteria = userexample.createCriteria();
		criteria.andUPhoneEqualTo(uphone);
		int uid = usermapper.selectByExample(userexample).get(0).getuId();
		MeiyouUser use = new MeiyouUser();
		use.setuId(uid);
		use.setuPassword(newpwd);
		if(usermapper.updateByPrimaryKeySelective(use)==1) {
			msg = Msg.success();
			return true;
		}
		return false;
	}
    
	
	
	public List<MeiyouUser> selUserByPhonePwd(String phone, String pwd, Double jindu, Double weidu) {
		// TODO Auto-generated method stub	
		System.out.println("登录"+jindu+","+weidu);
		
		
		List<MeiyouUser> list = usermapper.selectUserinfo(phone, pwd);
		System.out.println("用户大小"+list.size());
		if(jindu!=null&&weidu!=null) {
			if(list.size()==1) {
				Coordinate coordinate = new Coordinate();
				coordinate.setLatitude(weidu);
				coordinate.setLongitude(jindu);
				coordinate.setKey(list.get(0).getuCount());
				RedisUtil.addReo(coordinate,"test");
				return list;
			}
		}
		
		return list;
	}
	
	
	/**
	 * 通过手机号和密码登录
	 */
	
	public Msg selLoginByPwd(String phone,String pwd,Double jindu,Double weidu,HttpServletRequest req) {
		MeiyouUserExample example = new MeiyouUserExample();
		Msg msg;
		// TODO Auto-generated method stub
		MeiyouUserExample.Criteria criteria = example.createCriteria();
	    criteria.andUPhoneEqualTo(phone);
	    criteria.andUPasswordEqualTo(pwd);
	    List<MeiyouUser> users = usermapper.selectByExample(example);
	    if(users.size()==0) {
	    	msg = Msg.fail();
	    	msg.setMsg("用户名或密码错误");
	    }else {
	    	Coordinate coor = new Coordinate();
			coor.setLatitude(weidu);
			coor.setLongitude(jindu);
		    coor.setKey(phone);
		    RedisUtil.addReo(coor,"test");
		    msg = Msg.success();
	        req.getSession().setAttribute("user", phone);
	    }
	    return msg;
	}

	
	public int insUserByAlipayId(String uccount,String alipayId,String sex,String name,String img,HttpServletRequest req) {
		// TODO Auto-generated method stub
	
		MeiyouThir meiyouThir = new MeiyouThir();
		meiyouThir.settUCount(uccount);
		meiyouThir.settZfbcount(alipayId);
		MeiyouUser user = new MeiyouUser();
		user.setuCount(uccount);
		user.setuImg(img);
		user.setuSex(sex);
		user.setuName(name);
		user.setUmeijin(0);
		String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		user.setuTime(time);
		TecentService tecent = new TencentServiceImpl();
		if(tecent.registTencent(user))
			if(usermapper.insertSelective(user)==1)
				if(meiyouThirMapper.insertSelective(meiyouThir)==1) 
					return 1;
				
	   return 0;
	}

	
	public int updUserMeijin(double uMeijin,String uCount) {
		return userMapperCustom.updUserMeijin(uMeijin,uCount);
	}

	
	public String selUserPayByUcount(String uCount) {
		return userMapperCustom.selUserPayByUcount(uCount);
	}

	
	public String selUserByUcount(String uCount) {
		return userMapperCustom.selUserByUcount(uCount);
	}

   /**
    * 人脸对比
    */
	
	public Msg faceDuibi(MultipartFile file,String imgurl) {
		 Msg msg;
		 String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
		 String getAccessTokenUrl = authHost
	                // 1. grant_type为固定参数
	                + "grant_type=client_credentials"
	                // 2. 官网获取的 API Key
	                + "&client_id=" + "T9wuzB2ZnWdb9gVeGeQPAqS9"
	                // 3. 官网获取的 Secret Key
	                + "&client_secret=" + "m1YlbsYVntKHZS1mKskQHHnm75bLxeWk";
		 try {
			 URL realUrl = new URL(getAccessTokenUrl);
	            // 打开和URL之间的连接
	            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
	            connection.setRequestMethod("GET");
	            connection.connect();
	            // 获取所有响应头字段
	            Map<String, List<String>> map = connection.getHeaderFields();
	            // 遍历所有的响应头字段
	            for (String key : map.keySet()) {
	                System.err.println(key + "--->" + map.get(key));
	            }
	            // 定义 BufferedReader输入流来读取URL的响应
	            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	            String result = "";
	            String line;
	            while ((line = in.readLine()) != null) {
	                result += line;
	            }
	            /**
	             * 返回结果示例
	             */
	            System.err.println("result:" + result);
	            JSONObject jsonObject = new JSONObject(result);
	            String access_token = jsonObject.getString("access_token");
                
	            
            
            
	            String url = "https://aip.baidubce.com/rest/2.0/face/v3/match";
	            byte[] bytes1 = file.getBytes();
	            byte[] bytes2 = FileUtil.readFileByBytesOnline(imgurl);
	            String image1 = Base64Util.encode(bytes1);
	            String image2 = Base64Util.encode(bytes2);
     
	            List<Map<String, Object>> images = new ArrayList<Map<String, Object>>();
	            Map<String, Object> map1 = new HashMap<String, Object>();
	            map1.put("image", image1);
	            map1.put("image_type", "BASE64");
	            map1.put("face_type", "LIVE");
	            map1.put("quality_control", "LOW");
	            map1.put("liveness_control", "NORMAL");

	            Map<String, Object> map2 = new HashMap<String, Object>();
	            map2.put("image", image2);
	            map2.put("image_type", "BASE64");
	            map2.put("face_type", "LIVE");
	            map2.put("quality_control", "LOW");
	            map2.put("liveness_control", "NORMAL");

	            images.add(map1);
	            images.add(map2);
	            
	            String param = GsonUtils.toJson(images);
	            String result1 = HttpUtil.post(url, access_token, "application/json", param);
	            JSONObject json = new JSONObject(result1);
	            if(json.getInt("error_code")!=0) {
	            	msg = Msg.fail();
	            	msg.setMsg(json.getString("error_msg"));
	            	return msg;
	            }else {
	            	JSONObject obj = json.getJSONObject("result");
	            	Map<String,Object> map3 = new HashMap<String,Object>();
	            	    
	            		if(obj.getInt("score")>=80) {
		            		msg = Msg.success();
		            		
		            		map3.put("score", obj.getInt("score"));
		                    msg.setExtend(map3);
		            		return msg;
		            	}else {
		            		msg = Msg.fail();
		            		msg.setMsg("认证失败");
		            		map3.put("score",obj.getInt("score"));
		            		msg.setExtend(map3);
		            		return msg;
		            	}
	            	
	            	
	            }
            
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.err.printf("获取token失败！");
            e.printStackTrace(System.err);
            msg = Msg.fail();
            msg.setMsg("接口鉴权失败");
            return msg;
		}
		 
		
	}



	public static byte[] toByteArray(File file) throws IOException {

        
        ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
        BufferedInputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(file));
            int buf_size = 1024;
            byte[] buffer = new byte[buf_size];
            int len = 0;
            while (-1 != (len = in.read(buffer, 0, buf_size))) {
                bos.write(buffer, 0, len);
            }
            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            bos.close();
        }
    }


	
	public String selUserimg(String uccount) {
		// TODO Auto-generated method stub
		MeiyouUserExample example = new MeiyouUserExample();
		example.createCriteria().andUCountEqualTo(uccount);
		List<MeiyouUser> user = usermapper.selectByExample(example);
		return user.get(0).getuImg();
	}


	
	public Boolean updUserinfo(MeiyouUser user) {
		// TODO Auto-generated method stub
		
		/*
		 * MeiyouUserExample example = new MeiyouUserExample();
		 * MeiyouUserExample.Criteria criteria = example.createCriteria();
		 * criteria.andUCountEqualTo(user.getuCount());
		 * if(usermapper.updateByExample(user, example)==1) { return true; }else {
		 * return false; }
		 */
		if(usermapper.updataUserInfo(user)==1) {
			return true;
		}else {
			return false;
		}
	}
	
	public Boolean updUserinfoimg(MeiyouUser user) {
		// TODO Auto-generated method stub
		
		/*
		 * MeiyouUserExample example = new MeiyouUserExample();
		 * MeiyouUserExample.Criteria criteria = example.createCriteria();
		 * criteria.andUCountEqualTo(user.getuCount());
		 * if(usermapper.updateByExample(user, example)==1) { return true; }else {
		 * return false; }
		 */
		if(usermapper.updateUserimg(user)==1) {
			return true;
		}else {
			return false;
		}
	}

	
	public Boolean updAddUserMeijin(double meijin, String uccount) {
		// TODO Auto-generated method stub
		if(usermapper.updAddMeijin(meijin, uccount)>=1) {
			return true;
		}
		return false;
	}


	
	public Msg updPwdByUccount(String newPwd, String uccount) {
		Msg msg;
		// TODO Auto-generated method stub
		MeiyouUserExample example = new MeiyouUserExample();
		MeiyouUserExample.Criteria criteria = example.createCriteria();
		criteria.andUCountEqualTo(uccount);
		int uid = usermapper.selectByExample(example).get(0).getuId();
		MeiyouUser use = new MeiyouUser();
		use.setuId(uid);
		use.setuPassword(newPwd);
		if(usermapper.updateByPrimaryKeySelective(use)==1) {
			msg = Msg.success();
			return msg;
		}
	    msg = Msg.fail();
	    return msg;
	}

   //更新支付密码
	
	public Msg updPayPwdByUccount(String newPayPwd, String uccount) {
		Msg msg;
		// TODO Auto-generated method stub
		MeiyouUserExample example = new MeiyouUserExample();
		MeiyouUserExample.Criteria criteria = example.createCriteria();
		criteria.andUCountEqualTo(uccount);
		int uid = usermapper.selectByExample(example).get(0).getuId();
		MeiyouUser use = new MeiyouUser();
		use.setuId(uid);
		use.setuPayword(newPayPwd);
		if(usermapper.updateByPrimaryKeySelective(use)==1) {
			msg = Msg.success();
			return msg;
		}
	    msg = Msg.fail();
	    return msg;
	}


	
	public Msg updPwdByPhone(String newPwd, String phone) {
		// TODO Auto-generated method stub
		String uccount = usermapper.selectUcountByphone(phone);
		
		return updPwdByUccount(newPwd,uccount);
	}


	public Boolean updPhoneAndPwd(String pwd, String phone, String uccount) {
		// TODO Auto-generated method stub
		MeiyouUserExample example = new MeiyouUserExample();
		MeiyouUserExample.Criteria criteria = example.createCriteria();
		criteria.andUCountEqualTo(uccount);
		MeiyouUser user = new MeiyouUser();
		user.setuPhone(phone);
		user.setuPassword(pwd);
		if(usermapper.updateByExampleSelective(user, example)>=1) {
			return true; 
		}else {
			return false;
		}
		
	}


	public Boolean selCountByPhone(String phone) {
		// TODO Auto-generated method stub
		if(usermapper.selectCountByphone(phone)>=1) {
			return true;
		}else {
			return false;
		}
		
	}


	public MeiyouUser selUserByPhone(String phone) {
		// TODO Auto-generated method stub
		MeiyouUserExample example = new MeiyouUserExample();
		MeiyouUserExample.Criteria criteria = example.createCriteria();
		criteria.andUPhoneEqualTo(phone);
		List<MeiyouUser> users = usermapper.selectByExample(example);
		if(users.size()>0) {
			return users.get(0);
		}else {
			return null;
		}
		
	}


	public MeiyouUser selectUser(int id) {
		// TODO Auto-generated method stub
		return usermapper.selectByPrimaryKey(id);
	}
}
